import { HttpException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserEntity } from '../user/user.entity';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
  ) {}
  /**
   * 查询用户
   */
  async findOne(query): Promise<UserEntity> {
    return await this.userRepository.findOne({ where: query });
  }

  /**
   * 新建用户
   * @returns
   */
  async register(post: Partial<UserEntity>) {
    const accountExists = await this.findOne({ username: post.username });
    if (accountExists) throw new HttpException('此用户已被注册，请换一个', 400);

    await this.userRepository.save(post);
    return;
  }

  /**
   * 登录
   */
  async login(query: Partial<UserEntity>) {
    const { username, password } = query;
    const user = await this.findOne({ username });
    if (!user) throw new HttpException('用户不存在', 400);
    if (user.password !== password) throw new HttpException('密码错误', 400);

    return user;
  }

  /**
   * 获取用户信息
   */
  async getUserInfo(id) {
    const user = await this.findOne({ id });
    // 用户不存在重新登录
    if (!user) throw new HttpException('用户不存在', 401);

    return user;
  }
}
